package com.dferreira.languagesteach.data_parsers;

import com.dferreira.languagesteach.data_models.MetaSubject;
import com.dferreira.languagesteach.data_models.Lesson;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;

public class XMLLessonParser extends DefaultHandler {
    private final String LESSON_TAG = "lesson";

    private ArrayList<MetaSubject> metaSubjects;
    private Lesson lesson;

    /**
     * Starts the variables to the lesson parsing
     */
    public XMLLessonParser() {
        super();
    }

    /**
     * Called when tag starts
     *
     * @param uri        The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.
     * @param localName  The local name (without prefix), or the empty string if Namespace processing is not being performed.
     * @param qName      The qualified name (with prefix), or the empty string if qualified names are not available.
     * @param attributes The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object.
     */
    @Override
    public void startElement(String uri, String localName, String qName,
                             Attributes attributes) {
        String SUBJECT_TAG = "subject";
        String TITLE_ATTRIBUTE = "title";
        String FOLDER_ATTRIBUTE = "folder";

        if (localName.equals(LESSON_TAG)) {
            lesson = new Lesson();
            metaSubjects = new ArrayList<MetaSubject>();
        } else if (localName.equals(SUBJECT_TAG)) {
            MetaSubject metaSubject;
            metaSubject = new MetaSubject();
            metaSubject.setTitle(attributes.getValue(TITLE_ATTRIBUTE));
            metaSubject.setFolder(attributes.getValue(FOLDER_ATTRIBUTE));
            metaSubjects.add(metaSubject);
        }
    }

    /**
     * Called when tag ends
     *
     * @param uri       The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.
     * @param localName The local name (without prefix), or the empty string if Namespace processing is not being performed.
     * @param qName     The qualified name (with prefix), or the empty string if qualified names are not available.
     */
    @Override
    public void endElement(String uri, String localName, String qName) {
        if (localName.equals(LESSON_TAG)) {
            lesson.setMetaSubjects(metaSubjects);
        }
    }

    /**
     * @return the lesson and his subjects
     */
    public Lesson getLesson() {
        return lesson;
    }
}
